package com.zl.tby.service.impl;

import com.zl.tby.core.base.bean.TbyPageResult;
import com.zl.tby.core.base.util.ToolsUtil;
import com.zl.tby.core.common.R;
import com.zl.tby.dto.TbyCarRecordQuery;
import com.zl.tby.icc.IccCarRecord;
import com.zl.tby.icc.IccPageVo;
import com.zl.tby.icc.IccResponse;
import com.zl.tby.icc.IccUtil;
import com.zl.tby.model.TbyCarRecord;
import com.zl.tby.repository.TbyCarRecordRepo;
import com.zl.tby.service.ITbyCarRecordService;
import com.zl.tby.vo.TbyCarRecordForm;
import com.zl.tby.vo.TbyMonitoringStationForm;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;
import org.noear.wood.DbContext;
import org.noear.wood.IPage;
import org.noear.wood.annotation.Db;
import org.noear.wood.impl.IPageImpl;
import org.noear.wood.utils.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 车辆抓拍记录
 * @author changpeng
 * @version 1.0
 * @since 2024/8/6 20:22
 */
@Component
public class TbyCarRecordServiceImpl implements ITbyCarRecordService {

    @Db
    private TbyCarRecordRepo tbyCarRecordRepo;
    @Db
    private DbContext db;

    @Override
    @Tran
    public R<TbyCarRecord> add(TbyCarRecord entity) {
        entity.setCreateBy(-1L);
        entity.setCreateTime(LocalDateTime.now());
        long id = tbyCarRecordRepo.insert(entity, true);
        entity.setId(id);
        return R.ok(entity);
    }

    @Override
    public void addBatch(List<TbyCarRecord> entityList) {
        tbyCarRecordRepo.insertList(entityList);
    }

    @Override
    public TbyCarRecord get(Long id) {
        return tbyCarRecordRepo.selectById(id);
    }

    @Override
    public TbyPageResult<TbyCarRecordForm> page(TbyCarRecordQuery query) {
        IPage<TbyCarRecord> iPage = tbyCarRecordRepo.selectPage(query.getOffset(), query.getSize(), mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getDeviceCode()), "device_code = ?", query.getDeviceCode())
                    .andIf(StringUtils.isNotEmpty(query.getCarNum()), "car_num like ?", "%" + query.getCarNum() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getStartDate()), "cap_date >= ?", query.getStartDate() + " 00:00:00")
                    .andIf(StringUtils.isNotEmpty(query.getEndDate()), "cap_date <= ?", query.getEndDate() + " 23:59:59");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        List<TbyCarRecordForm> formList = new ArrayList<>();
        iPage.getList().forEach(item -> {
            formList.add(new TbyCarRecordForm(item));
        });
        return new TbyPageResult(new IPageImpl(formList, iPage.getTotal(), iPage.getSize()), query);
    }

    @Override
    public List<TbyCarRecordForm> list(TbyCarRecordQuery query) {
        List<TbyCarRecord> dataList = tbyCarRecordRepo.selectList(mp -> {
            mp.whereTrue()
                    .andIf(StringUtils.isNotEmpty(query.getDeviceCode()), "device_code = ?", query.getDeviceCode())
                    .andIf(StringUtils.isNotEmpty(query.getCarNum()), "car_num like ?", "%" + query.getCarNum() + "%")
                    .andIf(StringUtils.isNotEmpty(query.getStartDate()), "cap_date >= ?", query.getStartDate() + " 00:00:00")
                    .andIf(StringUtils.isNotEmpty(query.getEndDate()), "cap_date <= ?", query.getEndDate() + " 23:59:59");
            if (StringUtils.isNotEmpty(query.getOrder())) {
                mp.orderBy(query.getOrder());
            }
        });
        List<TbyCarRecordForm> formList = new ArrayList<>();
        for (TbyCarRecord entity : dataList) {
            formList.add(new TbyCarRecordForm(entity));
        }
        return formList;
    }

    @Override
    public void grab() {
        try {
            // 获取当前最近的抓拍时间，用作下一次的开始时间
            List<TbyCarRecord> dbList = db.table("tby_car_record").orderBy("cap_date desc").limit(1).selectList("cap_date", TbyCarRecord.class);
            // 开始时间
            Date startDate = null;
            if (dbList != null && dbList.size() > 0) {
                startDate = dbList.get(0).getCapDate();
                // 向后推迟一秒
                startDate = new Date(startDate.getTime() + 1000);
            } else {
                // 未空，就暂时获取当前日期的0点
                startDate = ToolsUtil.dateString2Util(ToolsUtil.dateUtil2String(new Date(System.currentTimeMillis()), "yyyy-MM-dd") + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            }
            Date endDate = new Date(System.currentTimeMillis());
            int page = 1;
            int pageNum = 200;
            while(true) {
                System.out.println("page: " + page);
                System.out.println("pageNum: " + pageNum);
                System.out.println("startDate: " + ToolsUtil.dateUtil2String(startDate, "yyyy-MM-dd HH:mm:ss"));
                System.out.println("endDate: " + ToolsUtil.dateUtil2String(endDate, "yyyy-MM-dd HH:mm:ss"));
                R<IccResponse<IccPageVo<IccCarRecord>>> r = IccUtil.searchCarRecordList(page, pageNum, startDate, endDate);
                if (r.getData().getCode().compareTo(1000) != 0) {
                    break;
                }
                List<IccCarRecord> list = r.getData().getData().getList();
                if (list == null || list.size() == 0) {
                    break;
                }
                List<TbyCarRecord> entityList = new ArrayList<>();
                for (IccCarRecord data : list) {
                    entityList.add(IccCarRecord.convert(data));
                }
                this.tbyCarRecordRepo.insertList(entityList);
                page++;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
